#!/usr/bin/env python3
"""
mcq-server.py - Main server.
Currently serves a diagnostic /info page and all other requests
as static files from the 'www' directory.
"""

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse         # separates path from query string
import config
import static_handler
import server_info


class RequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        print(f"--> Received GET {self.path}")

        # Separate the path from the query string for route matching
        parsed = urlparse(self.path)
        route_path = parsed.path

        if route_path == config.INFO_ROUTE:
            # Show the server diagnostics page
            server_info.handle(self)
        else:
            # Everything else: serve a file from www/
            static_handler.serve(self)

    def log_message(self, format, *args):
        print(f'{self.client_address[0]} - {format % args}')


if __name__ == '__main__':
    import os
    os.makedirs(config.PUBLIC_DIR, exist_ok=True)
    print(f'Starting server at http://{config.HOST}:{config.PORT}')
    server = HTTPServer((config.HOST, config.PORT), RequestHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print('\nShutting down.')
        server.server_close()